package com.swift.maintenance.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.jiyi.activity.TrainFragment;
import com.jiyi.activity.datainput.DataInputZoneFragment;
import com.jiyi.activity.main.MainFragment;
import com.jiyi.activity.mine.MineFragment;
import com.jiyi.activity.new_maintenance.ToolOwnerLeaderFragment;
import com.jiyi.activity.new_maintenance.ToolSupervisionAssistantFragment;
import com.jiyi.activity.new_maintenance.ToolSupervisionCaptainFragment;
import com.jiyi.activity.new_maintenance.ToolSupervisionStaffFragment;
import com.jiyi.activity.new_maintenance.ToolWbLeaderFragment;
import com.jiyi.activity.new_maintenance.ToolWbNormalFragment;
import com.jiyi.activity.zone.ZoneMainFragment;
import com.jiyi.easemob.util.EaseMobHelp;
import com.jiyi.event.RefreshHintEvent;
import com.jiyi.service.MessageService;
import com.jiyi.service.impl.MessageServiceImpl;
import com.swift.base.ActivityBase;
import com.swift.base.ApplicationBase;
import com.swift.inteface.ICheckUpdate;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.ActivityUtil;
import com.swift.utils.UpdateManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.view.annotation.ViewInject;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends ActivityBase implements OnClickListener,ICheckUpdate {

	private int currentIndex;


	@BindView(R.id.id_container)
	FrameLayout mFrameLayout;
	@BindView(R.id.ll_info)
	LinearLayout mInfoLinearLayout;
	@BindView(R.id.ll_repair)
	LinearLayout mRepairLinearLayout;
	@BindView(R.id.ll_me)
	LinearLayout mMeLinearLayout;
	@BindView(R.id.iv_info)
	ImageView mInfoImageView;
	@BindView(R.id.iv_repair)
	ImageView mRepairImageView;
	@BindView(R.id.iv_me)
	ImageView mMeImageView;
	@BindView(R.id.tv_info)
	TextView mInfoTextView;
	@BindView(R.id.tv_repair)
	TextView mRepairTextView;
	@BindView(R.id.tv_me)
	TextView mMeTextView;
	@BindView(R.id.ivMain)
	ImageView ivMain;

	@BindView(R.id.ll_train)
	LinearLayout mExitLinearLayout;
	@BindView(R.id.iv_train)
	ImageView mExitImageView;
	@BindView(R.id.tv_train)
	TextView mExitTextView;
	@ViewInject(R.id.iv_msg_hint)
	ImageView iv_msg_hint;

	final int CANCLE_BACK = 1;// 取消退出事件
	boolean isExit = false; // 是否退出标志
	int user_role;// 用户角色的类型
	// 当前页卡
	int currentMenuId = R.id.ivMain;
	// 消息服务
	MessageService mMessageService;
	// 是否首次进入
	boolean isFirst = true;
	final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 1;
	UpdateManager manager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ButterKnife.bind(this);
		getIntentData();
		setMenuByRole(user_role);
		initView();

		// 查找更新
		manager = new UpdateManager(this, AppConfig.VERSION_URL);
		manager.Update(this);


		EventBus.getDefault().register(this);

		if (isFirst) {
			// 初始化消息服务
			mMessageService = new MessageServiceImpl();
			// 获取未接收的消息
			mMessageService.getNoRecMsgList(UserInfoUtil
					.getCurrentUserAccessToken());
			isFirst = false;
			Log.e("开始获取服务器未接收的消息 ", "开始获取服务器未接收的消息");

			int size = mMessageService.getUnReadLocalMsg(
					UserInfoUtil.getCurrentUserAccount()).size();
			if (size > 0) {
				EventBus.getDefault().post(
						new RefreshHintEvent(RefreshHintEvent.MIME));
				Log.e("开始获取本地未读的消息 ", "已获取本地未读的消息" + size);
			}
		}
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onRefreshHint(RefreshHintEvent refreshHintEvent) {
		int type = refreshHintEvent.type;
		switch (type) {
		case RefreshHintEvent.MIME:
			int size = mMessageService.getUnReadLocalMsg(
					UserInfoUtil.getCurrentUserAccount()).size();
			displayHint(size > 0);
			break;

		default:
			break;
		}

	}
	
	

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-7-18
	 */
	private void getIntentData() {
		user_role = getIntent().getIntExtra("user_role", -1);
	}

	private void initView() {

		setFragment(new MainFragment(), "Home");

		mInfoLinearLayout.setOnClickListener(this);
		mRepairLinearLayout.setOnClickListener(this);
		ivMain.setOnClickListener(this);
		mMeLinearLayout.setOnClickListener(this);
		mExitLinearLayout.setOnClickListener(this);

	}

	private void setFragment(Fragment fragment, String tag) {
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();
		transaction.setCustomAnimations(R.anim.push_left_in,
				R.anim.push_left_out);
		transaction.replace(R.id.id_container, fragment, tag);
		transaction.commit();
	}

	@Override
	public void onClick(View v) {
		menuClickByRole(user_role, v);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exit();
			return false;
		}

		return super.onKeyDown(keyCode, event);
	}

	/**
	 * @author: HYM
	 * @Title: exit
	 * @Description: TODO(回退键退出功能)
	 * @param:
	 * @return: void
	 * @throws
	 */
	void exit() {
		if (isExit) {
			// 两次点击退出
			mHandler.removeCallbacksAndMessages(null);
			ActivityUtil.getInstances().exit();
		} else {
			// 点击一次提醒
			isExit = true;
			ToastUtil.getInstances().showMsg(R.string.IS_EXIT);
			mHandler.sendEmptyMessageDelayed(CANCLE_BACK, 2000);
		}
	}

	Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case CANCLE_BACK:
				isExit = false;
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onResume() {
		super.onResume();
		Boolean isLoginBoolean = EMClient.getInstance().isLoggedInBefore();
		Log.e("isLoginBoolean  ", isLoginBoolean + "");
		EaseMobHelp.getInstance().addGlobalListener();
	};

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		EaseMobHelp.getInstance().removeGlobalListener();
		super.onDestroy();
	};

	/**
	 * @author: HYM
	 * @Title: setMenuByRole
	 * @Description: TODO(初始化底部菜单)
	 * @param type
	 *            void
	 * @date: 2017-7-18
	 */
	void setMenuByRole(int type) {
		switch (type) {
		case AppConfig.ORG_LEADER:
		case AppConfig.ORG_MNG:
			// 监管
			initSupervisionMenu();
			break;
		case AppConfig.MTN_UNIT_LEADER:
		case AppConfig.MTN_UNIT_EMP:
			// 维保
			initWeiBaoMenu();
			break;
		case AppConfig.PROJECT_MNG:
		case AppConfig.PROJECT_EMP:
			// 业主
			initOwnerMenu();
			break;
		case AppConfig.GENERAL_USER:
		default:
			// 啥也不是类型
			initDefaultMenu();
			break;
		}
	}

	/**
	 * @author: HYM
	 * @Title: initDefaultMenu
	 * @Description: TODO(初始化默认的depart_type=-1的菜单) void
	 * @date: 2017-7-18
	 */
	void initDefaultMenu() {
		// 培训
		mRepairImageView.setImageResource(R.mipmap.icon_traning_normal);
		mRepairTextView.setTextColor(Color.parseColor("#cdcdcd"));
		mRepairTextView.setText("培训");
		// 社区
		mInfoImageView.setImageResource(R.mipmap.icon_zone_normal);
		mInfoTextView.setTextColor(Color.parseColor("#cdcdcd"));
		// 首页
		// 我的
		mMeImageView.setImageResource(R.mipmap.me);
		mMeTextView.setTextColor(Color.parseColor("#cdcdcd"));
		// 高层评估
		mExitImageView.setImageResource(R.mipmap.tab_build_normal);
		mExitTextView.setTextColor(Color.parseColor("#cdcdcd"));
		mExitTextView.setText("调查");
	}

	/**
	 * @author: HYM
	 * @Title: initWeiBaoMenu
	 * @Description: TODO(初始化类型=维保的菜单) void
	 * @date: 2017-7-18
	 */
	void initWeiBaoMenu() {
		// 维保
		mRepairImageView.setImageResource(R.mipmap.repair);
		mRepairTextView.setTextColor(Color.parseColor("#cdcdcd"));
		// 社区
		mInfoImageView.setImageResource(R.mipmap.icon_zone_normal);
		mInfoTextView.setTextColor(Color.parseColor("#cdcdcd"));
		// 首页
		// 我的
		mMeImageView.setImageResource(R.mipmap.me);
		mMeTextView.setTextColor(Color.parseColor("#cdcdcd"));
		// 高层评估
		mExitImageView.setImageResource(R.mipmap.tab_build_normal);
		mExitTextView.setTextColor(Color.parseColor("#cdcdcd"));
		mExitTextView.setText("调查");
	}

	void initOwnerMenu() {
		// 业主
		mRepairImageView.setImageResource(R.mipmap.repair);
		mRepairTextView.setTextColor(Color.parseColor("#cdcdcd"));
		mRepairTextView.setText("业主");
		// 社区
		mInfoImageView.setImageResource(R.mipmap.icon_zone_normal);
		mInfoTextView.setTextColor(Color.parseColor("#cdcdcd"));
		// 首页
		// 我的
		mMeImageView.setImageResource(R.mipmap.me);
		mMeTextView.setTextColor(Color.parseColor("#cdcdcd"));
		// 高层评估
		mExitImageView.setImageResource(R.mipmap.tab_build_normal);
		mExitTextView.setTextColor(Color.parseColor("#cdcdcd"));
		mExitTextView.setText("调查");
	}

	void initSupervisionMenu() {
		// 监管
		mRepairImageView.setImageResource(R.mipmap.repair);
		mRepairTextView.setTextColor(Color.parseColor("#cdcdcd"));
		mRepairTextView.setText("监管");
		// 社区
		mInfoImageView.setImageResource(R.mipmap.icon_zone_normal);
		mInfoTextView.setTextColor(Color.parseColor("#cdcdcd"));
		// 首页
		// 我的
		mMeImageView.setImageResource(R.mipmap.me);
		mMeTextView.setTextColor(Color.parseColor("#cdcdcd"));
		// 高层评估
		mExitImageView.setImageResource(R.mipmap.tab_build_normal);
		mExitTextView.setTextColor(Color.parseColor("#cdcdcd"));
		mExitTextView.setText("调查");
	}

	void menuClickByRole(int type, View v) {
		if (currentMenuId == v.getId()) {
			return;
		}
		setMenuByRole(type);
		switch (v.getId()) {
		case R.id.ivMain:
			// 全部都是首页，无需判断显示的菜单
			setFragment(new MainFragment(), "Home");
			break;
		case R.id.ll_repair:
			// 判断当前是什么类型的用户
			switch (type) {
			case AppConfig.ORG_LEADER:
			case AppConfig.ORG_MNG:
				// 监管
				mRepairImageView.setImageResource(R.mipmap.repair_press);
				mRepairTextView.setTextColor(Color.parseColor("#1296db"));
				mRepairTextView.setText("监管");
				// 监管
				if (UserInfoUtil.getCurrentUserSupervisionRole() == 1) {
					// 大队长
					setFragment(new ToolSupervisionCaptainFragment(), "Tool");
				} else if (UserInfoUtil.getCurrentUserSupervisionRole() == 2) {
					// 参谋
					setFragment(new ToolSupervisionStaffFragment(), "Tool");
				} else {
					// 助理
					setFragment(new ToolSupervisionAssistantFragment(), "Tool");
				}
				break;

			case AppConfig.MTN_UNIT_LEADER:
			case AppConfig.MTN_UNIT_EMP:
				// 维保类型
				if (!ApplicationBase.checkNetworkAvailable()) {
					Toast.makeText(this, "你现在处于离线状态，不支持进入维保", Toast.LENGTH_LONG)
							.show();
					return;
				}
				mRepairImageView.setImageResource(R.mipmap.repair_press);
				mRepairTextView.setTextColor(Color.parseColor("#1296db"));
				mRepairTextView.setText("维保");
				// setFragment(new MaintenanceFragment(), "Repair");
				if (UserInfoUtil.getCurrentUserRole() == 5) {
					// 主管
					setFragment(new ToolWbLeaderFragment(), "Tool");
				} else {
					// 普通维保人员
					setFragment(new ToolWbNormalFragment(), "Tool");
				}
				break;
			case AppConfig.PROJECT_MNG:
			case AppConfig.PROJECT_EMP:
				mRepairImageView.setImageResource(R.mipmap.repair_press);
				mRepairTextView.setTextColor(Color.parseColor("#1296db"));
				mRepairTextView.setText("业主");
				// 业主
				if (UserInfoUtil.getCurrentUserRole() == 2) {
					// 业主管理
					setFragment(new ToolOwnerLeaderFragment(), "Tool");
				}
				break;
			case AppConfig.GENERAL_USER:
			default:
				// 啥也不是类型
				mRepairImageView.setImageResource(R.mipmap.icon_traning_on);
				mRepairTextView.setTextColor(Color.parseColor("#1296db"));
				mRepairTextView.setText("培训");
				setFragment(new TrainFragment(), "Train");
				break;
			}
			break;

		case R.id.ll_info:
			// 全部都是社区，无需判断显示的菜单
			setFragment(new ZoneMainFragment(), "Zone");
			mInfoImageView.setImageResource(R.mipmap.icon_zone_on);
			mInfoTextView.setTextColor(Color.parseColor("#1296db"));

//			setFragment(new MainIotFragment(), "Iot");
//			mInfoImageView.setImageResource(R.mipmap.icon_zone_on);
//			mInfoTextView.setTextColor(Color.parseColor("#1296db"));

			break;

		case R.id.ll_me:
			// 全部都是我的，无需判断显示的菜单
			setFragment(new MineFragment(), "Me");
			mMeImageView.setImageResource(R.mipmap.me_press);
			mMeTextView.setTextColor(Color.parseColor("#1296db"));
			break;
		case R.id.ll_train:
			mExitImageView.setImageResource(R.mipmap.tab_build_on);
			mExitTextView.setTextColor(Color.parseColor("#1296db"));
			mExitTextView.setText("调查");
			// 全部都是商城，无需判断显示的菜单
//			if (UserInfoUtil.getCurrentUserAcessRole() == 2) {
//				// 录入员
//				setFragment(new ToolDataInputMainFragment(), "data");
//			} else {
//				// 其他
////				setFragment(new ToolDataInputViewFragment(), "data");
//				setFragment(new SMToolDataInputViewFragment(), "data");
//			}

			setFragment(new DataInputZoneFragment(),"data");
			break;
		default:
			break;
		}

		currentMenuId = v.getId();
	}

	void displayHint(boolean isShow) {
		if (isShow) {
			iv_msg_hint.setVisibility(View.VISIBLE);
		} else {
			iv_msg_hint.setVisibility(View.GONE);
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		doUpdate(requestCode,grantResults);
	}

	void doUpdate(int requestCode, int[] grantResults)
	{
		if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
			if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				// 查找更新
				manager.showDownloadDialog();
			} else {
				ToastUtil.getInstances().showMsg("无更新权限");
			}
		}


	}

	@Override
	public void checkUpdate() {
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
				!= PackageManager.PERMISSION_GRANTED) {
			//申请WRITE_EXTERNAL_STORAGE权限
			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
					WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
		}
		else
		{
			manager.showDownloadDialog();
		}
	}
}
